package com.watchthelan.service.schedule.event;

import java.util.Date;
import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.quartz.Job;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.SchedulerFactory;
import org.quartz.SimpleTrigger;
import org.springframework.context.ApplicationContext;

import com.watchthelan.domain.Event;
import com.watchthelan.domain.Server;
import com.watchthelan.repository.EventDao;
import com.watchthelan.service.schedule.job.SimpleJob;
import com.watchthelan.service.server.ServerManager;

public class SimpleEventManager implements EventManager {
	protected final Log logger = LogFactory.getLog(getClass());
	private EventDao eventDao;
	
	@Override
	public void addEvent(Event event) {
		eventDao.addEvent(event);
	}

	@Override
	public void deleteEventById(Long id) {
		eventDao.deleteEventById(id);
	}

	@Override
	public Event getEventById(Long id) {
		return eventDao.getEventById(id);
	}

	@Override
	public List<Event> getEvents() {
		return eventDao.getEvents();
	}

	@Override
	public void updateEvent(Event event) {
		eventDao.updateEvent(event);
	}

	public EventDao getEventDao() {
		return eventDao;
	}

	public void setEventDao(EventDao eventDao) {
		this.eventDao = eventDao;
	}
	
	public void scheduleEvent(Event event) throws SchedulerException {
		SchedulerFactory schedFact = new org.quartz.impl.StdSchedulerFactory();
		Scheduler sched = schedFact.getScheduler();
		
		JobDetail jobDetail = new JobDetail(event.getName(), sched.DEFAULT_GROUP, SimpleJob.class);
		Date startTime = new Date();
		startTime.setMonth(event.getMonth());
		startTime.setDate(event.getDay());
		startTime.setHours(event.getHour());
		startTime.setMinutes(event.getMinute());
		jobDetail.getJobDataMap().put("server_id", new Long(event.getServer()));
		
		SimpleTrigger simpleTrigger = new SimpleTrigger(event.getName(), sched.DEFAULT_GROUP, startTime);
		sched.deleteJob(event.getName(), sched.DEFAULT_GROUP);
		sched.scheduleJob(jobDetail, simpleTrigger);
		logger.info("scheduled event: " + event);
	}
}
